package com.color.admin.files.service.impl;

import com.color.admin.common.core.exception.BaseException;
import com.color.admin.common.core.utils.web.FileUtils;
import com.color.admin.files.service.FilesService;
import com.color.admin.files.service.entity.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HaiQiu
 * @date 2022/1/6
 */
@Service
public class FilesServiceImpl implements FilesService {

    @Autowired
    private SysFile sysFile;

    static String pics = "bmp，jpg，jpeg，png，tif，gif，pcx，tga，exif，fpx，svg，psd，cdr，pcd，dxf，ufo，eps，ai，raw，WMF，webp，avif，apng";
    static String videos = "wmv,avi,dat,asf,mpeg,mpg,rm,rmvb,ram,flv,mp4,3gp,mov,divx,dv,vob,mkv,qt,cpk,fli,flc,f4v,m4v,mod,m2t,swf,webm,mts,m2ts,3g2,mpe,ts,div,lavf,dirac,";
    static String audios = "mp3、aac/mp4、ape/flac、wav、wma、amr、mid";
    static String docs = "txt、doc、wps、docx、xls、xlsx、pdf";
    @Override
    public String upload(MultipartFile multipartFile, String folder) {
        return null;
    }

    @Override
    public Map<String,String> commonUpload(MultipartFile multipartFile) {

        String type = createFolder(multipartFile);

        String folder = sysFile.getStorage() + type;

        String fileName = FileUtils.upload(multipartFile, folder);

        String url = sysFile.getHttp() + type + fileName;
        Map<String,String> map = new HashMap<>(2);
        map.put("url",url);
        return map;
    }

    @Override
    public void commonDelete(String path) {
        if (!path.contains(sysFile.getHttp())){
            throw new BaseException("文件地址错误，删除失败");
        }
        String fileName = path.replace(sysFile.getHttp(), "");
        FileUtils.delete(sysFile.getStorage() + fileName);
    }


    public String createFolder(MultipartFile file){
        String o = file.getOriginalFilename();
        //前缀
        String prefix = o.substring(0, o.lastIndexOf("."));
        //后缀+1
        String suffix = o.substring(o.lastIndexOf(".")+1);
        return judgeType(suffix);
    }


    public String judgeType(String suffix){
        if (pics.contains(suffix)){
            return "picture" + File.separator;
        }else if (videos.contains(suffix)){
            return "video" + File.separator;
        }else if (audios.contains(suffix)){
            return "audio" + File.separator;
        }else if (docs.contains(suffix)){
            return "doc" + File.separator;
        }
        return "";
    }
}
